package com.developtools.actions;

import cn.torna.sdk.client.OpenClient;
import cn.torna.sdk.param.DocItem;
import cn.torna.sdk.request.DocPushRequest;
import cn.torna.sdk.response.DocPushResponse;
import com.alibaba.fastjson.JSON;
import com.developtools.constants.TornaConstant;
import com.developtools.converts.ClassApiConvert;
import com.developtools.model.ApiUploadModel;
import com.developtools.model.ClassApiInfo;
import com.developtools.model.SettingModel;
import com.developtools.utils.ApiUtils;
import com.developtools.utils.DataUtils;
import com.developtools.utils.NotificationUtils;
import com.developtools.view.ApiUploadDialogWrapper;
import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

import static com.developtools.constants.TornaConstant.*;
import static com.developtools.constants.TornaConstant.TOKEN;

public class RightScanBtn extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();
        if (Objects.isNull(project)){
            return;
        }
        ModuleManager moduleManager = ModuleManager.getInstance(project);
        DataUtils dataUtils = DataUtils.getInstance(project);

        ApiUploadModel apiUploadModel = new ApiUploadModel();
        Module[] modules = moduleManager.getModules();
        for (Module module : modules) {
            String name = module.getName();
            String value = dataUtils.getValue("t_token_" + name);
            apiUploadModel.getModuleMap().put(name, value);
        }

        String serverHost = dataUtils.getValue(TornaConstant.HOST);
        apiUploadModel.setServerHost(serverHost);

        ApiUploadDialogWrapper apiUploadDialogWrapper =new ApiUploadDialogWrapper(project, apiUploadModel);
        boolean b = apiUploadDialogWrapper.showAndGet();
        if (!b){
            return;
        }
        String selectedModule = apiUploadModel.getSelectedModule();
        if (StringUtils.isBlank(selectedModule)){
            return;
        }
        String serverHostModify = apiUploadModel.getServerHost();
        String token = apiUploadModel.getModuleMap().get(selectedModule);
        dataUtils.setValue(TornaConstant.HOST, serverHostModify);
        dataUtils.setValue("t_token_" + selectedModule, token);

        Optional<Module> moduleOptional = Stream.of(modules)
                .filter(m -> m.getName().equalsIgnoreCase(selectedModule)).findFirst();
        if (moduleOptional.isEmpty()){
            return;
        }
        List<ClassApiInfo> classApiInfos = ApiUtils.getApiForModule(project, moduleOptional.get());

        ProgressManager progressManager = ProgressManager.getInstance();

        Task.Backgroundable backgroundable = new Task.Backgroundable(project, "Up") {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                uploadTorna(project, classApiInfos, serverHostModify, token);
            }
        };
        progressManager.run(backgroundable);
    }

    private void uploadTorna(Project project, List<ClassApiInfo> classApiInfos, String host, String token) {
        OpenClient client = new OpenClient(host);
        DocPushRequest docPushRequest = new DocPushRequest(token);
        List<DocItem> folderList = ClassApiConvert.toFolderList(classApiInfos);
        docPushRequest.setApis(folderList);
        docPushRequest.setDebugEnvs(Lists.newArrayList());
        DocPushResponse execute = client.execute(docPushRequest);
        if (execute.isSuccess()){
            NotificationUtils.getInstance(project).send("Torna", "上传成功");
        }else {
            NotificationUtils.getInstance(project).error("Torna", "上传失败");
        }
    }
}
